package zgrjb.snbq.teach_platform.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zgrjb.snbq.teach_platform.dto.model.User;
import zgrjb.snbq.teach_platform.interceptor.LoginInterceptor;
import zgrjb.snbq.teach_platform.service.MessageService;
import zgrjb.snbq.teach_platform.util.JsonData;
import zgrjb.snbq.teach_platform.config.AIConfig;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.HashMap;

/**
 * 消息管理控制器
 * 
 * @author system
 * @since 2024-12-28
 */
@RestController
@RequestMapping("/api/v1/message")
@Slf4j
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private AIConfig aiConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送私聊消息
     */
    @PostMapping("/send")
    public JsonData sendMessage(@RequestBody SendMessageRequest request) {
        User user = LoginInterceptor.getCurrentUser();
        return messageService.sendPrivateMessage(user.getId(),
                                               request.getToUserId(),
                                               request.getContent(),
                                               request.getContentType());
    }

    /**
     * 获取用户消息列表
     */
    @GetMapping("/list")
    public JsonData getMessages(@RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "20") int size) {
        User user = LoginInterceptor.getCurrentUser();
        return messageService.getUserMessages(user.getId(), page, size);
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/read/{messageId}")
    public JsonData markAsRead(@PathVariable Long messageId) {
        User user = LoginInterceptor.getCurrentUser();
        return messageService.markAsRead(messageId, user.getId());
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public JsonData getUnreadCount() {
        User user = LoginInterceptor.getCurrentUser();
        return messageService.getUnreadCount(user.getId());
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{messageId}")
    public JsonData deleteMessage(@PathVariable Long messageId) {
        User user = LoginInterceptor.getCurrentUser();
        return messageService.deleteMessage(messageId, user.getId());
    }

    /**
     * 搜索用户进行私聊
     */
    @GetMapping("/search-users")
    public JsonData searchUsers(@RequestParam String keyword,
                               @RequestParam(required = false) String userType) {
        return messageService.searchUsers(keyword, userType);
    }

    /**
     * 获取会话列表
     */
    @GetMapping("/conversations")
    public JsonData getConversations() {
        User user = LoginInterceptor.getCurrentUser();
        return messageService.getConversations(user.getId());
    }

    /**
     * 获取会话消息
     */
    @GetMapping("/conversations/{conversationId}/messages")
    public JsonData getConversationMessages(@PathVariable String conversationId,
                                           @RequestParam(defaultValue = "1") int page,
                                           @RequestParam(defaultValue = "20") int size) {
        return messageService.getConversationMessages(conversationId, page, size);
    }

    /**
     * 获取AI智能建议
     */
    @PostMapping("/ai-suggestion")
    public JsonData getAISuggestion(@RequestBody Map<String, String> body) {
        String content = body.get("content");
        if (content == null || content.isEmpty()) {
            return JsonData.buildError("内容不能为空");
        }
        // 构造请求
        Map<String, Object> payload = new HashMap<>();
        payload.put("model", aiConfig.getModel());
        payload.put("messages", java.util.Arrays.asList(
                new HashMap<String, Object>() {{
                    put("role", "user");
                    put("content", content);
                }}
        ));
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.set("Authorization", "Bearer " + aiConfig.getKey());
        headers.set("Content-Type", "application/json");
        org.springframework.http.HttpEntity<Map<String, Object>> entity = new org.springframework.http.HttpEntity<>(payload, headers);
        try {
            org.springframework.http.ResponseEntity<Map> response = restTemplate.postForEntity(aiConfig.getUrl(), entity, Map.class);
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                // 解析智谱AI返回内容
                Object choices = response.getBody().get("choices");
                if (choices instanceof java.util.List && !((java.util.List) choices).isEmpty()) {
                    Object msg = ((java.util.Map)((java.util.List) choices).get(0)).get("message");
                    if (msg instanceof java.util.Map) {
                        String suggestion = (String) ((java.util.Map) msg).get("content");
                        return JsonData.buildSuccess(suggestion);
                    }
                }
                return JsonData.buildError("AI无有效回复");
            } else {
                return JsonData.buildError("AI接口调用失败");
            }
        } catch (Exception e) {
            return JsonData.buildError("AI调用异常: " + e.getMessage());
        }
    }

    /**
     * 发送消息请求体
     */
    public static class SendMessageRequest {
        private Long toUserId;
        private String content;
        private String contentType;

        // Getters and Setters
        public Long getToUserId() { return toUserId; }
        public void setToUserId(Long toUserId) { this.toUserId = toUserId; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getContentType() { return contentType; }
        public void setContentType(String contentType) { this.contentType = contentType; }
    }
} 